package demo.c2;

import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * FightQueryExample
 *
 * @author chisheng
 */
public class FightQueryExample {

    /**
     * Fight company list
     */
    private final static List<String> FIGHT_COMPANY = List.of("CSA", "CEA", "HNA");

    /**
     * Fight information search
     *
     * @param origin      origin
     * @param destination destination
     * @return information list
     */
    @SuppressWarnings("all")
    private static List<String> search(String origin, String destination) {
        final ArrayList<String> result = new ArrayList<>();
        final List<FightQueryTask> tasks = FIGHT_COMPANY.stream().map(company ->
                new FightQueryTask(company, origin, destination)
        ).collect(Collectors.toList());

        tasks.forEach(Thread::start);
        tasks.forEach(task -> {
            try {
                // 等待所有的线程都完成工作 main 线程才开始工作
                task.join();
            } catch (InterruptedException ignore) {
            }
        });

        tasks.stream().map(FightQueryTask::get).forEach(result::addAll);
        return result;
    }

    /**
     * Test
     */
    public static void main(String[] args) {
        final List<String> result = search("BJ", "SH");
        System.out.println("Result: " + result);
    }

}
